/**
 * Copyright (c) 2013 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.chargemybattery.actions;

import android.content.Context;
import android.provider.Settings;

public class ReduceBrightnessAction extends AbstractPowerSaveAction {
    private final int     minimumBrightness;
    private final Context context;
    private int           originalBrightness = -1;
    private final int     step               = 20;

    private ReduceBrightnessAction( Context aContext, int aMinimumBrightness ) {
        super();
        minimumBrightness = aMinimumBrightness;
        context = aContext;
    }

    @Override
    public void executeAction() {
        if ( originalBrightness == -1 ) {
            originalBrightness = Settings.System.getInt( context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 180 );
        }

        int theCurrentBrightness = Settings.System.getInt( context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 180 );
        // to not do anything if the brightness is already less then the minimum brightness
        if ( theCurrentBrightness > minimumBrightness ) {
            // reduce the brightness
            theCurrentBrightness -= step;
            // if the new brightness is less then the minimum change it to the minimum
            if ( theCurrentBrightness < minimumBrightness ) {
                theCurrentBrightness = minimumBrightness;
            }
            Settings.System.putInt( context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, theCurrentBrightness );
        }

    }

    @Override
    public void undo() {
        // only undo when the action was executed
        if ( originalBrightness != -1 ) {
            Settings.System.putInt( context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, originalBrightness );
        }
    }

    @Override
    public boolean isComplete() {
        return Settings.System.getInt( context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 180 ) == minimumBrightness;
    }

}
